<template>
  <el-dialog v-model="isShow" :close-on-click-modal="false">
    <template #header>
      <div class="title">
        <b>{{ data.title }}</b>
      </div>
    </template>
    <div class="content">
      <div class="div">
        <img
          :src="data.icon"
          style="width: 128px; height: 128px; padding: 0 10px"
        />
      </div>
      <div class="div">
        <el-text size="large" tag="b">{{ data.name }}</el-text>
        <el-text><el-tag>包名</el-tag>{{ data.package }}</el-text>
        <el-text><el-tag>版本号</el-tag>{{ data.versionName }}</el-text>
        <el-text><el-tag>大小</el-tag>{{ byte2mb(data.size) }}</el-text>
      </div>
    </div>
    <div class="content">
      <el-tag type="warning">应用说明</el-tag>
      <el-input
        v-model="data.mem"
        placeholder="请输入应用说明"
        :disabled="data.flag == 'del'"
        style="width: 300px; margin: 10px"
      />
    </div>
    <div
      class="content"
      v-if="!isNull(data.dtCreate)"
      style="padding-top: 10px"
    >
      <el-tag
        type="danger"
        size="large"
        v-if="data.flag == 'add'"
        style="margin-top: -20px; margin-right: 10px"
        >当前版本应用已存在</el-tag
      >
      <el-form-item label="上传时间" style="width: 360px">
        <span class="label">{{ data.dtCreate }}</span>
      </el-form-item>
    </div>
    <!-- <div class="content" v-if="!isNull(data.dtCreate)">
      <el-form-item label="上传者" style="width: 360px">
        <span class="label">{{ data.operCreate }}</span>
      </el-form-item>
    </div> -->
    <div class="content" v-if="!isNull(data.dtUpdate)">
      <el-form-item label="修改时间">
        <span class="label">{{ data.dtUpdate }}</span>
      </el-form-item>
      <el-form-item label="操作员">
        <span class="label">{{ data.operUpdate }}</span>
      </el-form-item>
    </div>
    <template #footer>
      <div class="footer">
        <el-button @click="close()">取 消</el-button>
        <el-button
          v-if="data.flag == 'del'"
          type="danger"
          @click="msgBox('del', '删除此应用')"
          >确认删除</el-button
        >
        <el-button v-else type="primary" @click="done()" :loading="loading">{{
          data.flag == "edit" ? "确认修改" : "确认上传"
        }}</el-button>
      </div>
      <div style="width: 80%;margin:auto;margin-top: 20px;text-align: center;" v-if="upProgress.v > 1">
        <p v-if="upProgress.v>=100">
          <el-text type="success" size="large" tag="b" v-if="upProgress.t=='SUCCESS'">上传成功</el-text>
          <el-text type="danger" size="large" tag="b" v-else>{{upProgress.t}}</el-text>
        </p>
        <el-progress v-else :text-inside="true" :stroke-width="24" :percentage="upProgress.v" status="success" />
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, reactive, ref } from "vue-demi";
import { ElMessageBox, ElNotification } from "element-plus";
import http from "@/axios/http";
import util from "@/assets/js/util";
import mqtt from '@/assets/js/mqtt';
export default {
  setup(props, ctx) {
    let isShow = ref(false);

    const Global = getCurrentInstance().proxy;
    let user = reactive({
      code: Global.$var.user.code,
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 202 || r.msgType == 204) {
            // console.log(d)
            ctx.emit("done", d);
            isShow.value = false;
          }
          if (r.msgType == 999001) {
          //console.log(d)
            tmpToken = d && d[0]?d[0].token:null
            if (!isNull(tmpToken)) {
              isShow.value = true;
            }
          }
        }
      })
    }

    // 获取临时token
    let tmpToken = null
    function getTmpToken() {
      tmpToken = null
      let msgCode = 999001;
      let topic = mqtt.TOPIC_REQ + msgCode;
      let p = {};
      p.msgType = msgCode;
      p.clientId = user.id;
      p.userName = user.username;
      p.message = {msg_type: '90200'};
    //console.log('获取临时token',JSON.stringify(p));
      mqtt.publish(topic, JSON.stringify(p));
    }

    let data = reactive({
      flag: "",
      id: "",
      title: "",
      versionCode: "",
      versionName: "",
      package: "",
      size: "",
      name: "",
      icon: "",
      mem: "",
      md5: "",
      vendor: "",
      url: "",
      file: null,
      dtCreate: "",
      operCreate: "",
    });

    let loading = ref(false);
    function open(file, d) {
      //console.log(d);
      // let qb_package = 'com.qb.devserv.xh,com.qb.devserv.hc,com.qb.devapps,com.qb.devtest'
      // if (util.hasStr(qb_package,d.package)) {
      //   d.appicon = '';
      // }
      mqttOnMsg()
      data.flag = d.flag;
      data.id = d.Id;
      data.title = d.application ? "上传应用" : "编辑应用信息";
      data.versionCode = d.ver_order;
      data.versionName = d.version;
      data.package = d.package_name;
      data.size = d.size;
      data.name = d.application ? apkName(d.application.label) : d.name;
      data.icon = d.appicon;
      data.mem = d.remark;
      data.md5 = d.md5;
      data.vendor = d.vendor
      data.url = d.url
      data.file = file;
      data.dtCreate = d.upload_time;
      data.operCreate = d.uploader_id;
      // data.dtUpdate = d.dtUpdate
      // data.operUpdate = d.operUpdate
      upProgress.v = 0;
      upProgress.t = '上传中…';
      getTmpToken();
    }

    function close() {
      isShow.value = false;
    }

    let upProgress = reactive({
      v: 0,
      t: '',
    })
    async function done() {
    //console.log(data);
      let m = "";
      if (data.flag !='del' && isNull(data.mem)) {
        m = "请输入应用说明";
      }
      if (isNull(m)) {
        let r = null;
        loading.value = true;
        let appInfo = {};
        appInfo.category = "默认类别";
        appInfo.name = data.name;
        appInfo.status = 0;
        appInfo.md5 = data.md5;
        appInfo.vendor = "";
        appInfo.version = data.versionName;
        appInfo.ver_order = data.versionCode;
        appInfo.package_name = data.package;
        appInfo.size = data.size;
        appInfo.url = data.url;
        appInfo.remark = data.mem;
        appInfo.uploader_id = user.code;
        //appInfo.appicon = data.icon
        if (data.flag == "add") {
          let file = data.file;
          let icon = util.base64ToFile(data.icon, "icon.jpg");
          r = await http.fileUpload(file, icon, appInfo, tmpToken, function(e) {
          //console.log('progress',e)
            upProgress.v = e
          });
        //console.log(r)
          loading.value = false;
          if (r) {
            upProgress.v = 100
            upProgress.t = r.message=='SUCCESS'?r.message:'上传失败'+r.message
          //console.log(upProgress.t)
            if (r.returnCode == 10000) {
              setTimeout(() => {
                ctx.emit("done", data);
                isShow.value = false;
              }, 500);
            }
          }
        }
        if (data.flag == "edit" || data.flag == "del") {
          let msgCode = 202;
          if (data.flag == "del") msgCode = 204;
          let topic = mqtt.TOPIC_REQ + msgCode;
          let p = {};
          p.msgType = msgCode;
          p.clientId = user.id;
          p.userName = user.username;
          p.message = {};
          if (data.flag == "edit") {
            appInfo.Id = data.id
            p.message.app = JSON.stringify(appInfo);
          }
          if (data.flag == "del") {
            p.message.appid = data.id
          }
        //console.log(data.flag+'应用列表',JSON.stringify(p));
          mqtt.publish(topic, JSON.stringify(p));
        }
      } else {
        ElNotification({
          type: "warning",
          title: "应用设置失败",
          message: m,
        });
      }
    }

    // 确认msgBox
    function msgBox(flag, msg, title = "是否确认？", cbt = "确认") {
      ElMessageBox.confirm(msg, title, {
        confirmButtonText: cbt,
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (flag == "del") done();
        })
        .catch(() => {});
    }

    function byte2mb(size) {
      size = size / 1024 / 1024;
      size = size.toFixed(1) + "MB";
      return size;
    }

    function apkName(label) {
      if (typeof label == "object") {
        return label[0];
      } else {
        return label;
      }
    }

    function isNull(v) {
      return util.isNull(v);
    }

    return {
      isShow,
      data,
      loading,
      open,
      close,
      upProgress,
      done,
      msgBox,
      byte2mb,
      apkName,
      isNull,
    };
  },
};
</script>

<style lang="scss" scoped>
.title {
  width: 100%;
}
.content {
  @extend %view-flex;
  flex-direction: row;
  .div {
    @extend %view-flex;
    width: auto;
    .el-text {
      width: 100%;
      padding: 3px 10px;
      .el-tag {
        margin: 0 3px;
      }
    }
  }
  .label {
    background-color: $color-primary-away;
    // border: 1px solid $color-primary-light;
    padding: 0px 15px;
    border-radius: 1px;
    margin-right: 20px;
  }
}
.footer {
  @extend %view-flex;
  flex-direction: row;
}
</style>